<?php

namespace common\modules\wechat\controllers\backend;

use common\modules\wechat\models\backend\ReplyRuleForm;
use common\modules\wechat\models\backend\ReplyRuleSearch;
use common\modules\wechat\models\ReplyRule;
use common\modules\wechat\models\ReplyKeyword;
use common\modules\wechat\components\AdminController;
use common\widgets\ActiveForm;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * 模块回复规则控制
 *
 * @package common\modules\wechat\controllers\backend
 */
class ReplyController extends AdminController
{

    /**
     * 扩展模块回复列表
     *
     * @return mixed
     */
    public function actionIndex()
    {
        // 一定要先选择管理公众号
        if ( ! $this->getWechat())
        {
            return $this->flash(self::FLASH_MSG_TYPE_ERROR, '请先选择管理公众号', ['account/index']);
        }

        $searchModel = new ReplyRuleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere([
            'wid' => $this->getWechat()->id, // 公众号过滤
        ]);

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        return $page->render();
    }

    /**
     * Creates a new ReplyRule model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        // 一定要先选择管理公众号
        if ( ! $this->getWechat())
        {
            return $this->flash(self::FLASH_MSG_TYPE_ERROR, '请先选择管理公众号', ['account/index']);
        }

        $model = new ReplyRuleForm(['scenario' => ReplyRuleForm::SCENARIO_CREATE]);
        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            $model->wid = $this->getWechat()->id;

            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                $ruleKeyword = new ReplyKeyword;
                $ruleKeywords = [];
                if ($this->save($model, $ruleKeyword, $ruleKeywords))
                {
                    return $this->flash(self::FLASH_MSG_TYPE_SUCCESS, '添加成功!', ['update', 'id' => $model->id]);
                }
                else
                {
                    Yii::$app->session->setFlash('danger', '创建失败!');
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            ReplyRuleForm::SCENARIO_CREATE,
            [
                'pageTitle' => '创建规则',
            ]
        );
        return $page->render();
    }

    /**
     * Updates an existing ReplyRule model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        // 一定要先选择管理公众号
        if ( ! $this->getWechat())
        {
            return $this->flash(self::FLASH_MSG_TYPE_ERROR, '请先选择管理公众号', ['account/index']);
        }

        $model = $this->findModel($id);
        $model->setScenario(ReplyRuleForm::SCENARIO_UPDATE);

        $ruleKeyword = new ReplyKeyword();
        $ruleKeywords = $model->keywords;

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($this->save($model, $ruleKeyword, $ruleKeywords))
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_SUCCESS, '更新成功!');
                    $model->refresh();
                }
                else
                {
                    Yii::$app->session->setFlash(self::FLASH_MSG_TYPE_ERROR, '更新失败!');
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            ReplyRuleForm::SCENARIO_UPDATE,
            [
                'pageTitle' => '更新规则',
            ]
        );
        return $page->render();
    }

    /**
     * Deletes an existing ReplyRule model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $mid = $model->mid;
        $model->delete();

        return $this->redirect(['index', 'mid' => $mid]);
    }

    /**
     * 保存内容
     *
     * @param ReplyRule    $rule
     * @param ReplyKeyword $keyword
     * @param array        $keywords
     * @return bool
     */
    protected function save($rule, $keyword, $keywords = [])
    {
        if ( ! $rule->save())
        {
            return false;
        }
        $_keywords = ArrayHelper::index($keywords, 'id');
        $keywords = [];
        $valid = true;
        foreach (Yii::$app->request->post($keyword->formName(), []) as $k => $data)
        {
            if ( ! empty($data['id']) && $_keywords[$data['id']])
            {
                $_keyword = $_keywords[$data['id']];
                unset($_keywords[$data['id']]);
            }
            else
            {
                $_keyword = clone $keyword;
            }
            unset($data['id']);
            $keywords[] = $_keyword;
            $_keyword->setAttributes(array_merge($data, [
                'rid' => $rule->id,
            ]));
            $valid = $valid && $_keyword->save();
        }

        // 无更新的则删除
        ! empty($_keywords) && ReplyKeyword::deleteAll(['id' => array_keys($_keywords)]);

        return $valid;
    }

    /**
     * Finds the ReplyRule model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return ReplyRule the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ReplyRuleForm::findOne($id)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
